<template>
    <div class="divSureAddTask divWarehouse">
        <div class="divContent box">
            <div class="divTable">
              <div  v-if="tableData.length>0">
                  <div class="divProgress">
                    <div class="divLabel">上架进度</div>
                    <div class="divContainer">
                      <div class="divInnner" :style="{width: progress.width}"></div>
                    </div>
                    <div class="divLabel">{{progress.percent}}</div>
                  </div>
                  <el-table
                  :data="tableData"
                  stripe
                  border
                  style="width: 100%"
                  v-loading="loading"
                  :header-cell-style="{ background: '#f9f6ee' }"
                  >
                  <el-table-column
                      type="index"
                      align="center"
                      width="68"
                      label="序号"
                  />
                  <el-table-column
                      prop="goodsCode"
                      align="center"
                      label="货品编号"
                      width="160"
                  />
                  <el-table-column
                      prop="goodsName"
                      align="center"
                      label="货品名称"
                      width="160"
                  />
                  <el-table-column
                      prop="goodsTypeName"
                      align="center"
                      label="货品类型"
                      width="160"
                  />
                  <el-table-column
                      prop="ownerName"
                      align="center"
                      label="货主名称"
                      width="160"
                  />
                  <el-table-column
                      prop="warehouseName"
                      align="center"
                      label="仓库"
                      width="160"
                  />
                  <el-table-column
                      prop="realNum"
                      align="center"
                      label="货品数量"
                      width="160"
                  />
                  <el-table-column
                      prop="groundingNum"
                      align="center"
                      label="实上数量"
                      width="150"
                  />
                  <el-table-column
                      prop="realNum"
                      align="center"
                      label="差异数"
                      width="160"
                  >
                      <template  slot-scope="{row}">
                          <span>{{row.groundingNum - row.realNum}}</span>
                      </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="250" fixed="right">
                                <template slot-scope="{row}">
                                  <base-button class="fontOperateButton" v-if="!isDetails"  @click="editMsg(row)">填写上架信息</base-button>
                                  <base-button class="fontOperateButton" v-else  @click="editMsg(row)">查看上架信息</base-button>
                                </template>
                  </el-table-column>

                  </el-table>
                  <!-- 分页 -->
                  <base-pagination :total="paging.total" :limit="paging.size" @current-change="handleCurrentChange"  @size-change="handleSizeChange"></base-pagination>
              </div>
              <div
                  v-else
                  class="emptyTip"
              >
                  <span class="imgIcon"></span>
                  <p>暂无收货任务</p>
              </div>
            </div>
            <div class="buttonBox">
              <base-button
                  class="unimportanceButton"
                  @click="btnReturnClick"
              >返回</base-button>
              <base-button
                  class="minorImportantButton"
                  @click="btnSubmitClick"
                  v-if="!isDetails"
              >提交</base-button>
            </div>
        </div>
        <div  class="divDialog">
            <el-dialog :title="dialogData.title" :visible.sync="dialogData.visible" width="1080px">
              <div class="divDesc">
                <el-row :gutter="94">
                  <el-col :span="4">
                    <p class="pLable">货品编号</p>
                    <p class="pValue">{{dialogData.item.goodsCode}}</p>
                  </el-col>
                  <el-col :span="4">
                    <p class="pLable">货品名称</p>
                    <p class="pValue">{{dialogData.item.goodsName}}</p>
                  </el-col>
                  <el-col :span="4">
                    <p class="pLable">货品类型</p>
                    <p class="pValue">{{dialogData.item.goodsTypeName}}</p>
                  </el-col>
                  <el-col :span="4">
                    <p class="pLable">货品数量</p>
                    <p class="pValue">{{dialogData.item.realNum}}</p>
                  </el-col>
                  <el-col :span="4">
                    <p class="pLable">货主名称</p>
                    <p class="pValue">{{dialogData.item.ownerName}}</p>
                  </el-col>
                  <!-- <el-col :span="4">
                    <p class="pLable">推荐库区</p>
                    <p class="pValue">{{dialogData.item.areaName}}</p>
                  </el-col> -->
                </el-row>
              </div>
              <div class="tableInfo" v-if="!isDetails">
                <base-button
                class="importantButton"
                @click="btnClickAddLocation"
                >添加库位</base-button>
              </div>
              <div v-else style="margin-top:20px"></div>
              <el-scrollbar style="height:351px">
                <div class="divTable">
                <el-table
                    :data="dialogData.tableData"
                    border
                    style="width: 99%"
                    ref="dialogTable"
                    :row-class-name="rowClassName"
                    v-loading="loading"
                    :header-cell-style="{ background: '#f9f6ee' }"
                >
                    <el-table-column
                        type="location"
                        align="center"
                        label="实上库位"
                        width="380"
                    >
                    <template slot-scope="{row}">
                      <el-cascader  v-model="(dialogData.tableData)[row.xh-1].location"
                          :props="cascaderOptions.props"
                          clearable
                          style="width:100%"
                          :disabled="isDetails === undefined ? false : true"
                      >
                      </el-cascader>
                    </template>
                    </el-table-column>
                    <el-table-column
                        prop="num"
                        align="center"
                        label="实上数量"
                        width="380"
                    >
                    <template slot-scope="{row}">
                      <el-input-number v-model="(dialogData.tableData)[row.xh-1].num" controls-position="right" :min="0" style="width:100%" :disabled="isDetails"/>
                    </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" >
                      <template slot-scope="{ row }">
                        <base-button class="fontOperateButton"  @click="btnDeleteLocationClick(row.xh -1)" v-if="!isDetails">删除</base-button>
                      </template>
                    </el-table-column>
                </el-table>
              </div>
              </el-scrollbar>
                <div slot="footer" class="dialog-footer">
                  <base-button  class="unimportanceButton btnCancle" @click="dialogData.visible = false">返回</base-button>
                  <base-button class="minorImportantButton" type="primary" @click="btnSureClick" v-if="!isDetails">提交</base-button>
                </div>
          </el-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import { mixins } from 'vue-class-component'
import { Component, Watch } from 'vue-property-decorator'
import SinglePage from '@/mixin/single-page'
import BaseButton from '@/components/base-button/index.vue'
import BasePagination from '@/components/base-pagination/index.vue'
import { IWarehouseInListLocationPlanEntity, IWarehouseInListTableData } from '@/module-storage-in/interface/warehouse-in-list'
import { findWarehouseInListDetailPaging, updateWarehouseInList, findSumWarehouseInList } from '@/module-storage-in/api/warehouse-in-list'
import { getAllWarehouse } from '@/module-base/api/warehouse'
import { IWarehouseTableData } from '@/module-base/interface/warehouse'
import { getAllAreaList } from '@/module-base/api/area'
import { IAreaTableData } from '@/module-base/interface/area'
import { getAllLocationList } from '@/module-base/api/location'
import { ICommonReturn } from '@/utils/common-interface'

interface ILocationTableData {
  location:number[] // 实上库位
  num:number // 数量
}

@Component({
  name: 'SureAddTaskConfirm',
  components: {
    BaseButton,
    BasePagination
  }
})
export default class extends mixins(SinglePage) {
    private tableData:IWarehouseInListTableData[] = []

    private progress = {
      percent: '',
      width: '0px'
    }

    private loading = false

    private paging = {
      current: 1, // 当前页码
      size: 10, // 每页数据量
      total: 0
    }

    private dialogData = {
      tableData: [] as ILocationTableData[],
      title: '填写上架信息',
      visible: false,
      id: 0,
      item: {} as IWarehouseInListTableData,
      ownerId: ''
    }

    private cascaderOptions = {
      props: {
        lazy: true,
        lazyLoad: async(node:any, resolve:any) => {
          const { level } = node
          if (level === 0) {
            const { data } = await getAllWarehouse({ status: 1, ownerId: this.dialogData.ownerId })
            const nodes = data.map((item:IWarehouseTableData) => {
              return {
                value: item.id,
                label: item.name,
                leaf: level >= 2 // 不设置的话点击第一级菜单也会触发change事件  文本区域也会填充
              }
            })
            resolve(nodes)
          } else if (level === 1) {
            const { data } = await getAllAreaList({ warehouseId: node.value, status: 1 })
            let nodes = []
            if (data) {
              nodes = data.map((item:IAreaTableData) => {
                return {
                  value: item.id,
                  label: item.name,
                  leaf: level >= 2// 不设置的话还会继续加载下一级菜单
                }
              })
            }
            resolve(nodes)
          } else if (level === 2) {
            const { data } = await getAllLocationList({ areaId: node.value })
            let nodes = []
            if (data) {
              nodes = data.map((item:IAreaTableData) => {
                return {
                  value: item.id,
                  label: item.name,
                  leaf: level >= 2// 不设置的话还会继续加载下一级菜单
                }
              })
            }
            resolve(nodes)
          }
        }
      }
    }

    private isDetails = ''

    private rowClassName({ row = {} as any, rowIndex = 0 }) {
      row.xh = rowIndex + 1
    }

    created() {
      this.initData()
    }

    @Watch('dialogData.visible', { immediate: true })
    private onRouteChange(visible:boolean) {
      if (!visible) {
        this.dialogData.tableData = []
      }
    }

    private initData() {
      this.getList()
      this.isDetails = this.$route.params.detail
      if (this.isDetails) {
        this.dialogData.title = '查看上架信息'
      }
    }

    private async getList() {
      this.loading = true
      const params = {
        masterId: this.$route.params.id,
        current: this.paging.current,
        size: this.paging.size
      }
      Promise.all([findWarehouseInListDetailPaging(params), findSumWarehouseInList(this.$route.params.id)])
        .then(res => {
          this.loading = false
          this.tableData = res[0].data.records.map((item:IWarehouseInListTableData) => {
            return { ...item, edit: false }
          })
          this.paging.total = parseInt(res[0].data.total, 10)
          // 进行进度条数据的设置
          this.progress.percent = res[1].data.goodsGroundingTotal + '/' + res[1].data.goodsRealTotal
          this.progress.width = (200 * res[1].data.goodsGroundingTotal / res[1].data.goodsRealTotal) + 'px'
        })
    }

    private btnSubmitClick() {
      this.closeWindow()
    }

    private btnReturnClick() {
      this.closeWindow()
    }

    private handleCurrentChange(page: number) {
      this.paging.current = page
      this.getList()
    }

    private handleSizeChange(page: number) {
      this.paging.size = page
      this.paging.current = 1
      this.getList()
    }

    private editMsg(row:IWarehouseInListTableData) {
      if (!row.locationPlanEntities || row.locationPlanEntities.length === 0) {
        row.locationPlanEntities = row.recommendLocationPlanEntities
      }
      this.dialogData.tableData = row.locationPlanEntities.map((item:IWarehouseInListLocationPlanEntity) => {
        return {
          location: [item.warehouseId, item.areaId, item.locationId],
          num: item.num
        }
      })
      this.dialogData.ownerId = String(row.ownerId)
      this.dialogData.id = row.id
      this.dialogData.item = row
      this.dialogData.visible = true
    }

    private btnClickAddLocation() {
      this.dialogData.tableData.push({
        location: [],
        num: 0
      })
    }

    private btnDeleteLocationClick(index:number) {
      if (this.confirmMsg()) {
        return
      }
      this.dialogData.tableData.splice(index, 1)
    }

    private async btnSureClick() {
      const tableData = this.dialogData.tableData
      const recommendLocationPlanEntities = [] as any
      let groundingNum = 0
      let flag = true
      tableData.forEach(item => {
        if (item.location && item.location.length === 3 && item.num !== undefined) {
          recommendLocationPlanEntities.push({
            warehouseId: item.location[0],
            areaId: item.location[1],
            locationId: item.location[2],
            num: item.num
          })
          groundingNum += item.num
        } else {
          flag = false
        }
      })
      if (!flag) {
        this.$message.error('任务有未填写项，不能完成')
        return
      }
      const data = ((await updateWarehouseInList({
        id: this.dialogData.id,
        locationPlanEntities: recommendLocationPlanEntities,
        groundingNum
      })) as unknown) as ICommonReturn
      if (data.code === 0) {
        this.$message.success('上架信息填写成功')
        this.getList()
        this.dialogData.visible = false
      } else {
        this.$message.error(data.msg)
      }
    }
}
</script>

<style scoped lang="scss">
.divSureAddTask{
  .divContent {
    padding-bottom: 20px;
    .divProgress{
      padding:32px 0 40px 20px;
      .divLabel,.divContainer{
        float: left;
      }
      .divLabel{
        height: 18px;
        font-size: 13px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #332929;
        line-height: 18px;
      }
      .divContainer{
        margin:6px 18px 5px 14px;
        height: 7px;
        background-color: #F6F1F0;
        border-radius: 7px;
        width: 200px;
        .divInnner{
          height: 7px;
          background-image: linear-gradient(to right,  rgba(0, 190, 118, 1), rgba(110, 230, 150, 1));
          border-radius: 7px;
        }
      }

    }
    .buttonBox{
      margin:0
    }
  }
    ::v-deep .el-dialog{
      border-radius: 2px;
      .el-scrollbar__wrap {
          overflow-x: hidden;
      }
      .el-dialog__header{
        background: #ffffff;
        box-shadow: 0px 0px 6px 0px rgba(144,142,142,0.17);
      }
      .el-dialog__footer{
        text-align: center;
        border: 1px solid #f5efee;
        height: 90px;
        padding-top: 25px;
        button{
          width: 170px;
        }
      }

      .divDesc{
        padding-top: 12px;
        padding-bottom: 16px;
        p{
          padding-top: 8px;
        }
        .pLable{
          font-size: 13px;
          font-family: PingFangSC, PingFangSC-Medium;
          font-weight: 500;
          color: #887e7e;
        }
        .pValue{
          font-size: 13px;
          font-family: PingFangSC, PingFangSC-Regular;
          font-weight: 400;
          color: #332929;
        }
      }
      .tableInfo{
        padding-left: 0px;
      }

      //下边的样式是设置表格行悬浮颜色
      .el-table tbody tr:hover>td {
          background-color:#ffffff!important
      }
      .hover-row{
        background-color:#ffffff!important
      }
      .hover-row > td {
        background-color:#ffffff!important
      }
    }
}

</style>
